<template>
  <div class="page">

    <!-- 搜索区域 开始 -->
    <div class="el_card_box">
      <el-form :inline="true" size="small" :model="formInline" class="search_form">
        <el-form-item label="关键词：">
          <el-input v-model="formInline.searchField" placeholder="用户姓名、手机号码"></el-input>
        </el-form-item>
        <el-form-item label="用户角色：">
          <el-select v-model="formInline.roleId" class="a_select" placeholder="请选择">
            <el-option v-for="(item, index) in roleList" :key="index" :label="item.roleName" :value="item.roleId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门：">
          <!-- <el-popover v-model="showSearchPopover" placement="bottom" width="400" trigger="click">
            <el-tree :data="optionsTree" highlight-current @node-click="searchNodeClick"></el-tree>
            <el-input slot="reference" v-model="formInline.departmentName" :suffix-icon="showSearchPopover?'el-icon-arrow-up':'el-icon-arrow-down'" class="a_input" readonly placeholder="所属部门"></el-input>
          </el-popover> -->
          <depart-ment v-model="formInline.departmentId" @change="onChange"></depart-ment>
        </el-form-item>
        <el-form-item label="状态：">
          <el-select v-model="formInline.userStatus" class="a_select" placeholder="请选择">
            <el-option label="已启用" value="1"></el-option>
            <el-option label="已禁用" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="search_btn_box">
        <el-button type="primary" size="small" @click="getList(1)">筛选</el-button>
        <el-button type="default" size="small" @click="rest">清空筛选</el-button>
      </div>
    </div>
    <!-- 搜索区域 end -->

    <!-- 表格 开始 -->
    <div class="table_box">
      <!-- 操作区域 开始 -->
      <div class="action_box">
        <el-button type="primary" size="small" @click="openDialog()">新增用户</el-button>
      </div>
      <!-- 操作区域 end -->

      <el-table ref="elTable" class="el_table" size="small" :data="tableData">
        <el-table-column prop="departmentName" label="所属部门" />
        <el-table-column prop="roleName" label="所属角色" />
        <el-table-column prop="username" label="用户名称" />
        <el-table-column prop="phoneNumber" label="手机号" />
        <el-table-column prop="status" label="状态">
          <template slot-scope="{row}">{{ row.enableStatus == 1 ? '已启用' : '已禁用' }}</template>
        </el-table-column>
        <el-table-column prop="createdDate" label="创建时间" />
        <el-table-column prop="address" label="操作" width="180">
          <template slot-scope="{row}">
            <el-link type="primary" class="el_link" @click="updateUserInfo(row)">{{ row.enableStatus == 1 ? '禁用' : '启用' }}
            </el-link>
            <el-link type="primary" class="el_link" @click="openDialog(row)">编辑</el-link>
            <el-link type="danger" class="el_link" @click="remove(row)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination_list">
        <el-pagination background layout="sizes, total,prev, pager, next, jumper" :total="pageTotal" :page-size="pageSize"
          :page-sizes="pageSizes" :current-page.sync="pageNumber" @current-change="getList"
          @size-change="changePageSize" />
      </div>
    </div>
    <!-- 表格 end -->

    <!-- 新增账号-弹框 开始 -->
    <glsx-dialog :show="showDialog" :title="userId ? '编辑用户' : '新增用户'" width="40%" @close="closeDialog">
      <div class="add_acount">
        <el-form :model="addForm" ref="addForm" :rules="addFormRules" label-width="120px" v-if="showDialog">
          <el-form-item label="所属部门：" prop="departmentName">
            <el-popover v-model="showPopover" placement="bottom" width="400" trigger="click">
              <el-tree :data="optionsTree" highlight-current @node-click="nodeClick"></el-tree>
              <!-- <el-button slot="reference">click 激活</el-button> -->
              <el-input slot="reference" v-model="addForm.departmentName"
                :suffix-icon="showPopover ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" class="a_input" readonly
                placeholder="所属部门"></el-input>
            </el-popover>
            <!-- <el-cascader class="a_input" :disabled="currentId?true:false" :options="optionsTree" v-model="addForm.departmentId" :props="{ checkStrictly: true,value:'id', label:'label',expandTrigger:'click',emitPath:false }" clearable></el-cascader> -->
          </el-form-item>
          <el-form-item label="用户角色：" prop="roleId">
            <el-select v-model="addForm.roleId" class="a_select" placeholder="请选择">
              <el-option v-for="(item, index) in roleList" :key="index" :label="item.roleName" :value="item.roleId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="关联来源：">
            <el-tree ref="adTree" :check-strictly="false" :props="treeProps" :data="adTreeData" highlight-current
              show-checkbox node-key="id" @check-change="onTreeCheck">
            </el-tree>
          </el-form-item>
          <el-form-item label="关联医院：">
            <el-tree ref="hospitalTree" :check-strictly="false" :props="treeProps" :data="hospitalTreeData"
              highlight-current show-checkbox node-key="id" @check-change="onHospitalTreeCheck">
            </el-tree>
          </el-form-item>
          <el-form-item label="用户名称：" prop="username">
            <el-input v-model="addForm.username" class="a_input" placeholder="用户名称"></el-input>
          </el-form-item>
          <el-form-item label="手机号码：" prop="phoneNumber">
            <el-input v-model="addForm.phoneNumber" class="a_input" placeholder="手机号码" maxlength="11"
              autocomplete="new-password"></el-input>
          </el-form-item>
          <el-form-item label="登录密码：" prop="password" v-if="!addForm.id">
            <el-input type="password" v-model="addForm.password" class="a_input" placeholder="登录密码"
              autocomplete="new-password"></el-input>
          </el-form-item>
          <el-form-item label="登录密码：" v-if="addForm.id">
            <el-input type="password" v-model="addForm.password" class="a_input" placeholder="登录密码"
              autocomplete="new-password"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="" slot="footer">
        <el-button size="small" type="primary" @click="saveInfo()">确定</el-button>
        <el-button size="small" type="default" @click="closeDialog">取消</el-button>
      </div>
    </glsx-dialog>
    <!-- 新增账号-弹框 end -->
  </div>
</template>

<script>
import {
  GETUSERSEARCH,
  GETROLESIMPLELIST,
  GETORGANIZATIONSIMPLEROOT,
  GETUSERINFO,
  DELETEUSERINFO,
  ADDUSERINFO,
  EDITUSERINFO,
  ORGANIZATIONSIMPLEROOT,
  GETORGANIZATIONSIMPLELIST,
  GETORGANIZATIONTREE,
  GETCHANNELSOURCECOMPOUNDOPTIONS,
  GETHOSPITALCOMPOUNDOPTIONS,
  UPDATEUSERSTATUS,
} from "@/http/system";
import GlsxDialog from "@/components/Dialog/index";
import { showModal, showToast } from "@/common/util";
import _ from "lodash";
export default {
  components: {
    GlsxDialog,
  },
  data() {
    return {
      formInline: {},
      tableData: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      searchText: "",
      treeData: [],
      pageTotal: 0,
      pageNumber: 1,
      pageSizes: [10, 20, 50, 100],
      pageSize: 20,
      loading: false,
      showDialog: false,
      addForm: { adSourceIds: [] },
      roleList: [],
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            max: 50,
            min: 2,
            message: "请输入2-50个字符的用户名",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { max: 18, min: 6, message: "请输入6-18位的密码", trigger: "blur" },
        ],
        phoneNumber: [
          { required: true, message: "请输入手机号", trigger: "blur" },
        ],
        departmentName: [
          { required: true, message: "请选择所属部门", trigger: "blur" },
        ],
        roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
        adSourceIds: [
          { required: true, message: "请选择关联来源", trigger: "change" },
        ],
        hospitalIds: [
          { required: true, message: "请选择关联医院", trigger: "change" },
        ],
      },
      userId: "",
      optionsTree: [],
      currentId: "",
      showPopover: false,
      treeProps: {
        children: "children",
        label: "name",
      },
      adTreeData: [],
      adTreeDataList: [],
      hospitalTreeData: [],
      showSearchPopover: false,
    };
  },
  mounted() {
    this.getList();
    this.getRoles();
    this.getOrganization();
    this.getAdTree();
    this.getHospital();
  },
  methods: {
    /** 获取用户列表 */
    getList(current) {
      let _this = this;
      let oParams = _this.getParams();
      oParams.pageNumber = current || _this.pageNumber;
      console.log(oParams);
      _this.loading = true;
      GETUSERSEARCH(oParams).then((res) => {
        console.log(res);
        _this.loading = false;
        let obj = res.data || {};
        _this.tableData = obj.list || [];
        _this.pageTotal = obj.totalElements;
      });
    },
    /** 每页展示 */
    changePageSize(e) {
      this.pageSize = e;
      this.getList();
    },

    /** 获取参数 */
    getParams() {
      let o = JSON.parse(JSON.stringify(this.formInline));
      o.pageSize = this.pageSize;
      return o;
    },

    /** 重置 */
    rest() {
      this.formInline = {};
      this.pageNumber = 1;
      this.getList();
    },

    // 获取角色列表
    getRoles() {
      GETROLESIMPLELIST().then((res) => {
        this.roleList = res.data || [];
      });
    },

    // 获取一级组织机构
    getOrganization() {
      GETORGANIZATIONTREE().then((res) => {
        let list = res.data || [];
        this.optionsTree = list[0] ? list[0].children : [];
      });
    },

    // 打开新增弹框
    openDialog(row) {
      console.log(row);
      if (row) {
        this.userId = row.id;
        GETUSERINFO({ id: row.id }).then((res) => {
          let o = {};
          let m = res.data || {};

          o.id = m.id;
          o.username = m.username;
          o.phoneNumber = m.phoneNumber;
          o.departmentId = m.departmentId;
          o.departmentName = m.departmentName;
          //o.dataType = m.dataType;
          o.account = m.account;
          //o.enableStatus = m.enableStatus;
          o.roleId = m.roleId;
          o.adSourceIds = m.adSourceIds;
          o.hospitalIds = m.hospitalIds;
          o.channelSourceIds = m.channelSourceIds;

          // 设置勾选
          (m.adSourceIds || []).map((k) => {
            let _node = this.$refs.adTree.getNode(`c${k}`);
            console.log(_node);
            if (_node.isLeaf && _node.level > 1) {
              this.$refs.adTree.setChecked(_node, true);
            }
          });

          (m.channelSourceIds || []).map((k) => {
            let _node = this.$refs.adTree.getNode(k);
            this.$refs.adTree.setChecked(_node, true);
          });

          // 设置医院勾选
          m.hospitalIds.map((k) => {
            let _node = this.$refs.hospitalTree.getNode(k);
            if (_node.isLeaf && _node.level > 1) {
              this.$refs.hospitalTree.setChecked(_node, true);
            }
          });

          this.addForm = o;
        });
      }
      this.showDialog = true;
    },

    // 关闭新增弹框
    closeDialog() {
      this.showDialog = false;
      this.userId = "";
      this.addForm = {};
      this.$refs.addForm.clearValidate();
    },

    // 保存数据
    saveInfo() {
      let _this = this;
      _this.$refs.addForm.validate((valid) => {
        if (!valid) {
          return false;
        }
        let arr = [];
        let adSourceIds = [];
        let o = JSON.parse(JSON.stringify(_this.addForm));
        o.account = o.phoneNumber;

        if (o.adSourceIds && o.adSourceIds.length) {
          o.adSourceIds.map((k) => {
            if (!k.pid) {
              arr.push(k.id);
            } else {
              adSourceIds.push(k.id.replace(/c/, ""));
            }
          });
        }

        o.adSourceIds = adSourceIds;
        o.channelSourceIds = arr;

        console.log(o);
        // 编辑
        if (_this.userId) {
          EDITUSERINFO(o).then((res) => {
            if (res.code == 200) {
              showToast({
                message: "编辑成功",
                type: "success",
              });
              _this.closeDialog();
              _this.getList();
            }
          });
          return false;
        }

        ADDUSERINFO(o).then((res) => {
          if (res.code == 200) {
            showToast({
              message: "新增成功",
              type: "success",
            });
            _this.closeDialog();
            _this.getList();
          }
        });
      });
    },

    // 删除账号
    remove(row) {
      let _this = this;
      showModal({
        message: "确定删除该账号吗？",
        showCancelButton: true,
        success: function () {
          DELETEUSERINFO({ id: row.id }).then((res) => {
            if (res.code == 200) {
              showToast({
                message: "删除成功",
                type: "success",
              });
              _this.getList();
            }
          });
        },
      });
    },

    // 监听树节点点击
    nodeClick(data) {
      this.addForm.departmentId = data.id;
      this.addForm.departmentName = data.label;
      console.log(this.addForm);
      this.showPopover = false;
      this.$refs.addForm.clearValidate("departmentName");
    },

    // 监听树节点点击
    searchNodeClick(data) {
      this.formInline.departmentId = data.id;
      this.formInline.departmentName = data.label;
      this.showSearchPopover = false;
    },

    // 获取广告树
    getAdTree() {
      GETCHANNELSOURCECOMPOUNDOPTIONS().then((res) => {
        let list = res.data || [];
        this.adTreeData = list;
        this.adTreeDataList = this.flattenDeep(list);
      });
    },

    // 监听树节点选中
    onTreeCheck(node, e) {
      let o = this.$refs.adTree.getCheckedNodes(false, true);
      console.log(o);
      this.addForm.adSourceIds = o;
      this.$refs.addForm.clearValidate("adSourceIds");
    },

    // 监听医院树节点选中
    onHospitalTreeCheck() {
      let o = this.$refs.hospitalTree.getCheckedKeys(true);
      this.addForm.hospitalIds = o;
      this.$refs.addForm.clearValidate("hospitalIds");
    },

    // 展开数组
    flattenDeep(arr, list = []) {
      arr.map((k) => {
        list.push(k);
        if (k.children) {
          this.flattenDeep(k.children, list);
        }
      });
      return list;
    },

    // 获取医院树形数据
    getHospital() {
      GETHOSPITALCOMPOUNDOPTIONS().then((res) => {
        this.hospitalTreeData = res.data;
      });
    },

    // 启用停用
    updateUserInfo(row) {
      let _this = this;
      // todo
      let _type = {
        1: "禁用",
        2: "启用",
      };
      showModal({
        message: `确定${_type[row.enableStatus]}该账号吗？`,
        showCancelButton: true,
        type: "warning",
        success: function () {
          let oParams = {};
          oParams.id = row.id;
          UPDATEUSERSTATUS(oParams).then((res) => {
            if (res.code == 200) {
              showToast({
                message: "操作成功",
                type: "success",
              });
              _this.getList();
            }
          });
        },
      });
    },

    // 监听组织树
    onChange(id) {
      console.log(id)
      //this.$set(this.formInline,'departmentId',id)
    }

  },
};
</script>

<style lang="scss" scoped>
.content_box {
  display: flex;

  .left_tree {
    width: 200px;
    font-size: 12px;
  }

  .right_box {
    flex: 1;
    box-sizing: border-box;
    padding: 0 10px;
  }
}

.stop_status,
.normal_status {
  position: relative;
  padding-left: 10px;
  color: #f00;
}

.normal_status {
  color: #31b311;
}

.stop_status:after,
.normal_status:after {
  display: block;
  content: "";
  width: 8px;
  height: 8px;
  border-radius: 100%;
  background: #f00;
  position: absolute;
  left: 0;
  top: 50%;
  transform: translate(0, -50%);
}

.normal_status:after {
  background: #31b311;
}

.add_acount {

  .a_input,
  .a_select {
    width: 300px;
  }
}
</style>
